<template>
  <div class="offer-edit-container">
    <el-drawer :title="title === 'add' ? '新增': title === 'check'? '查看' :title === 'edit'?'编辑': '复制' "
               :visible.sync="dialogVisible"
               :modal-append-to-body="false"
               :append-to-body="true"
               top="10px"
               :close-on-press-escape="false"
               :wrapperClosable="false" :before-close="handleClose" size="60%">
      <el-divider></el-divider>
      <el-form ref="form" :model="form" :rules="rules" label-width="150px" style="width: 90%;margin: 0 auto"
               v-loading="loading">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="订单名称:" prop="name">
              <el-input id="id-business-offeredit-form-name"
                        :disabled="title === 'check'" size="mini"
                        v-model="form.name" placeholder="请输入订单名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产品名:" prop="productName">
              <el-input id="id-business-offeredit-form-productName"
                        :disabled="title === 'check'"
                        size="mini" placeholder="请输入产品名"
                        v-model="form.productName">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12" v-if="userInfo.is_agency === 1">
            <el-form-item label="客户:" prop="customerId">
              <el-select id="id-business-offeredit-customerChange"
                         :disabled="title === 'check'"
                         placeholder="请选择客户"
                         v-model="form.customerId" filterable size="mini" @change="customerChange">
                <el-option v-for="(item,index) in customerList" :key="index" :value="item.id"
                           :label="item.name" :disabled="disableId.indexOf(item.id) !== -1">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="(userInfo.is_agency == 0 && form.isShared == 1) || userInfo.is_agency == 1">
            <el-form-item label="广告主审核素材:" prop="auditCreative">
              <el-radio-group :disabled="title === 'check'" v-model="form.auditCreative">
                <el-radio :label="true">是</el-radio>
                <el-radio :label="false">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12" v-if="isTenantIds">
            <el-form-item label="团队:" prop="team">
              <el-select
                :disabled="title === 'check'"
                placeholder="请选择团队"
                v-model="form.team" filterable size="mini" @change="handleChangeTeam">
                <el-option
                  v-for="(item,index) in deptList"
                  :key="index"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20" v-if="userInfo.is_agency !== 0">
          <el-col :span="12">
            <el-form-item label="优化师:" prop="optimized">
              <el-select v-model="selectedOptimizers" placeholder="请选择" size="mini" multiple filterable
                         :disabled="title === 'check'">
                <el-option
                  v-for="item in optimizerList"
                  v-if="item.deptId.includes(form.team)"
                  :key="item.id"
                  :label="item.realName"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设计师:" prop="designer">
              <el-select v-model="selectedDesigners" placeholder="请选择" size="mini" multiple filterable
                         :disabled="title === 'check'">
                <el-option
                  v-for="item in designerList"
                  v-if="item.deptId.includes(form.team)"
                  :key="item.id"
                  :label="item.realName"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12" v-if="title === 'edit' || title === 'check'||title === 'copy'">
            <el-form-item label="客户经理:">
              <el-input id="id-business-offeredit-form-customerManager"
                        size="mini"
                        :disabled="true"
                        v-model="form.customerManager">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="title === 'check' || title === 'edit'||title === 'copy'">
            <el-form-item label="销售经理:">
              <el-input id="id-business-offeredit-form-salesManager"
                        size="mini"
                        :disabled="true"
                        v-model="form.salesManager">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12" v-if="title === 'check' || title === 'edit'||title === 'copy'">
            <el-form-item label="订单Id:">
              <el-input id="id-business-offeredit-form-Id"
                        size="mini"
                        :disabled="true"
                        v-model="form.id">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <!--        <el-row>-->
        <!--          <el-col span="12">-->
        <!--            <el-form-item label="等级:" prop="level" :rules="{required:roles.admin,message:'请选择等级'}">-->
        <!--              <el-select id="id-offer-edit-level" :disabled="title === 'check' || !roles.admin" v-model="form.level">-->
        <!--                <el-option v-for="(item,index) in levelList" :key="index" :value="item.value" :label="item.label">-->
        <!--                </el-option>-->
        <!--              </el-select>-->
        <!--            </el-form-item>-->
        <!--          </el-col>-->
        <!--        </el-row>-->
        <el-row>
          <el-form-item label="操作系统" prop="system">
            <div style="padding: 15px;border-radius: 15px;border: 1px solid #eee;">
              <el-row>
                <el-col :span="24">
                  <el-form-item label="Android" label-width="80px">
                    <div v-if="title !== 'check' && (offerStatus === 0 || !offerStatus)" @click="addApp"
                         class="addAppStyle"> 新增App
                    </div>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col>
                  <el-form-item label="商店URL:" prop="androidAppId" label-width="80px">
                    <el-select id="id-business-offeredit-form-androidAppId" v-model="form.androidAppId"
                               style="width: 100%" clearable
                               :disabled="title === 'check' ||  iosDisable"
                               size="mini">
                      <el-option v-for="item in androidList" :key="item.appUrl" :value="item.id"
                                 :label="item.name">
                        <div style="display: flex">
                          <div style="width: 40px;height: 40px;margin-right: 8px">
                            <img style="width: auto;height: auto;max-height: 100%;max-width: 100%" :src="item.logoUrl"
                                 alt="">
                          </div>
                          <div>
                            {{ item.name }}
                          </div>
                        </div>
                      </el-option>
                    </el-select>
                    <!--                    <el-input :disabled="title === 'check'|| androidDisable " size="mini"-->
                    <!--                              v-model="form.androidAppId"></el-input>-->
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="投放地区:" prop="androidNation" label-width="80px">
                    <el-select :disabled="title === 'check'"
                               v-model="form.androidNation" multiple clearable
                               filterable placeholder="请选择" size="mini">
                      <el-option
                        v-for="(item,index) in nationList"
                        :key="index"
                        :label="item.cnName"
                        :value="item.geoKey">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="媒体:" prop="androidPlatform" label-width="80px">
                    <el-select :disabled="title === 'check'"
                               id="androidPlatform" v-model="form.androidPlatform" clearable
                               multiple size="mini">
                      <el-option v-for="(item,index) in platformsList" :key="index" :value="item.dictKey"
                                 :label="item.dictValue" @change="form.androidPlatform.join(',')">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24">
                  <el-form-item label="IOS" label-width="80px">
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col>
                  <el-form-item label="商店URL:" prop="iosAppId" label-width="80px">
                    <!--                    <el-input size="mini" :disabled="title === 'check' ||  iosDisable"-->
                    <!--                              v-model="form.iosAppId"></el-input>-->
                    <el-select id="id-business-offeredit-form-iosAppId" v-model="form.iosAppId" style="width: 100%"
                               clearable
                               :disabled="title === 'check' ||  iosDisable" size="mini">
                      <el-option v-for="item in iosList" :key="item.appUrl" :value="item.id"
                                 :label="item.name">

                        <div style="display: flex">
                          <div style="width: 40px;height: 40px;margin-right: 8px">
                            <img style="width: auto;height: auto;max-height: 100%;max-width: 100%" :src="item.logoUrl"
                                 alt="">
                          </div>
                          <div>
                            {{ item.name }}
                          </div>
                        </div>
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="投放地区:" prop="iosNation" label-width="80px">
                    <el-select :disabled="title === 'check'" id="iosCountry"
                               v-model="form.iosNation" multiple clearable
                               filterable placeholder="请选择" size="mini">
                      <el-option
                        v-for="(item,index) in nationList"
                        :key="index"
                        :label="item.cnName"
                        :value="item.geoKey">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="媒体:" prop="iosPlatform" label-width="80px">
                    <el-select :disabled="title === 'check'" id="iosPlatform" v-model="form.iosPlatform" multiple
                               clearable
                               size="mini">
                      <el-option v-for="(item,index) in platformsList" :key="index" :value="item.dictKey"
                                 :label="item.dictValue" size="mini">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24">
                  <el-form-item label="Website" label-width="80px">
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col>
                  <el-form-item label="URL:" prop="websiteAppId" label-width="80px">
                    <!--                    <el-input size="mini" :disabled="title === 'check' ||  iosDisable"-->
                    <!--                              v-model="form.iosAppId"></el-input>-->
                    <el-select v-model="form.websiteAppId" style="width: 100%" clearable
                               :disabled="title === 'check' ||  iosDisable" size="mini">
                      <el-option v-for="item in websiteList" :key="item.appUrl" :value="item.id"
                                 :label="item.name">

                        <div style="display: flex">
                          <div style="width: 40px;height: 40px;margin-right: 8px">
                            <img style="width: auto;height: auto;max-height: 100%;max-width: 100%" :src="item.logoUrl"
                                 alt="">
                          </div>
                          <div>
                            {{ item.name }}
                          </div>
                        </div>
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="投放地区:" prop="websiteNation" label-width="80px">
                    <el-select :disabled="title === 'check'" id="iosCountry"
                               v-model="form.websiteNation" multiple clearable
                               filterable placeholder="请选择" size="mini">
                      <el-option
                        v-for="(item,index) in nationList"
                        :key="index"
                        :label="item.cnName"
                        :value="item.geoKey">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="媒体:" prop="websitePlatform" label-width="80px">
                    <el-select :disabled="title === 'check'" id="iosPlatform" v-model="form.websitePlatform" multiple
                               clearable size="mini">
                      <el-option v-for="(item,index) in platformsList" :key="index" :value="item.dictKey"
                                 :label="item.dictValue">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </el-form-item>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item prop="remark" label="备注">
              <el-input id="id-business-offeredit-form-remark"
                        :disabled="title === 'check'"
                        type="textarea"
                        v-model="form.remark"
                        size="mini"
                        autosize>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20" v-if="userInfo.is_agency === 0">
          <el-col :span="24">
            <el-form-item label="设置">
              <div style="padding: 15px;border-radius: 15px;border: 1px solid #eee;">
                <el-row>
                  <el-col :span="12">
                    <el-form-item prop="isShared" label="内外订单" label-width="80px">
                      <el-select id="id-business-offeredit-form-isShared" :disabled="title === 'check'"
                                 v-model="form.isShared">
                        <el-option v-for="(item,index) in isSharedDicData" :key="index" :value="item.value"
                                   :label="item.label">
                        </el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <div v-if="title === 'check'" style="background: #f0f2f5;padding: 15px;margin-top: 30px;border-radius: 15px">
          <offer-share :open-check="openCheck" :offer-id="editId" :offer-info="getOfferInfo(editId)"
                       :confirm-to-share="confirmToShare"></offer-share>
        </div>
      </el-form>
      <el-row :gutter="20">
        <el-col :span="24" style="text-align: center">
          <el-button id="id-business-offeredit-handleSubmit" :disabled="title === 'check'"
                     size="mini" icon="el-icon-circle-plus-outline" type="primary"
                     @click="handleSubmit">保存
          </el-button>
          <el-button size="mini" icon="el-icon-circle-close" @click="handleClose">取消</el-button>
        </el-col>
      </el-row>
    </el-drawer>


    <!-- 新增App-->
    <el-dialog title="新增App" :visible.sync="appDialogVisible" :modal-append-to-body="false"
               :append-to-body="true" :close-on-click-modal="false" :before-close="handleAppClose">
      <el-form :model="addForm" label-width="120px" ref="addForm" :rules="addRules">
        <el-form-item prop='customer' label="客户:" v-if="userInfo.is_agency === 1">
          <el-select id="id-business-offeredit-addForm-customerId" v-model="addForm.customerId" disabled
                     style="width: 50%" size="mini">
            <el-option v-for="(item,index) in customerList" :key="index" :value="item.id"
                       :label="item.name">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="isWebsite">
          <el-radio-group v-model="addForm.isWebsite" @change="websiteControl">
            <el-radio :label="false">商店 URL</el-radio>
            <el-radio :label="true">website URL</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item prop="appUrl" label="商店URL:">
          <el-input id="id-business-offeredit-addForm-appUrl" v-model="addForm.appUrl" size="mini"
                    style="width: 80%"></el-input>
        </el-form-item>
        <el-row :gutter="20" v-if="addForm.isWebsite || formVisible">
          <el-col :span="12">
            <el-form-item label="产品名称:" prop="name">
              <el-input id="id-business-offeredit-addForm-name" size="mini" v-model="addForm.name"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="包名:" prop="appPackageId">
              <el-input id="id-business-offeredit-addForm-appPackageId" size="mini"
                        v-model="addForm.appPackageId"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20" v-if="addForm.isWebsite || formVisible">
          <el-col :span="12">
            <el-form-item label="类型:" prop="category">
              <el-input id="id-business-offeredit-addForm-category" size="mini" v-model="addForm.category"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="!addForm.isWebsite">
            <el-form-item label="操作系统:">
              <el-select v-model="addForm.os" size="mini" :disabled="addForm.isWebsite" placeholder="请选择">
                <el-option
                  v-for="item in osList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="addForm.isWebsite">
            <el-form-item label="操作系统:">
              <el-input disabled size="mini" placeholder="website"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="!addForm.isWebsite && formVisible">
          <el-col :span="12">
            <el-form-item label="上传图标:">
              <el-upload
                class="avatar-uploader"
                action="#"
                :show-file-list="false"
                :http-request="uploadQiniuCloud"
                :before-upload="beforeAvatarUpload"
                list-type="picture">
                <img v-if="imageUrl" :src="imageUrl" class="avatar">
                <i v-else class="el-icon-upload2"></i>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>

        <div style="display: flex;justify-content: flex-end;margin-right: 10%;margin-top: 20px">
          <el-button v-if="urlconfirm && !addForm.isWebsite" size="mini" type="success" :loading="urlLoading"
                     @click="urlConfim">校验
          </el-button>
          <el-button v-else id="id-business-offeredit-saveApp" type="primary" size="mini" @click="saveApp"
                     :loading="app_save_loading">保 存
          </el-button>
          <el-button id="id-business-offeredit-handleAppClose" size="mini" @click="handleAppClose">取 消</el-button>
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>

import {getSysDictList, getGeoList} from '@/api/system/dict'
import {add, update, customer, getCustomerManager, getSalesManager} from "@/api/business/offer";
import {getShareCustomer} from "@/api/business/customer";
import offerShare from "./offerShare";
import {mapGetters} from "vuex";
import {getOfferList} from "@/api/business/share";
import {getAppUrlSelect, addApp, verifyProductUrl} from "@/api/business/appManager"
import {syncLevel} from "../../../api/business/customer";
import {getDesignerSelect, getOptimizer} from "@/api/offer/creative";
import * as qiniuTools from "@/util/qinnu_upload";
import {getWorkrooms} from "@/api/accountOrTransfer/account";


export default {
  name: 'offerEdit',
  components: {offerShare},
  props: {
    confirmToShare: {
      type: Number
    },
    isTenantIds:{
      type: Boolean
    },
    title: {
      type: String,
    },
    dialogVisible: {
      type: Boolean
    },
    dataList: {
      type: Object | String
    },
    offerStatus: {
      type: Number |  String
    }
  },
  computed: {
    ...mapGetters(["permission", "userInfo", "roles"]),
  },
  watch: {
    dataList: {
      deep: true,
      handler(val, old) {
        if (val === old) {
          return
        }
        this.editId = val.id
        this.openCheck = true
        this.status = val.status
        this.analysis(val)
        this.initPage();
        this.managerList.map(item => {
          if (item.id === this.form.salesManager) {
            this.form.salesManager = item.realName
          }
        })
        this.customerManagerList.map(item => {
          if (item.id === this.form.customerManager) {
            this.form.customerManager = item.realName
          }
        })
      }
    },
    offerStatus: {
      deep: true,
      handler(val) {
        this.initPage();
        if (val == 1 || val == 2) {
          this.disabled = true
          this.iosDisable = this.form.iosAppId !== ''
          this.androidDisable = this.form.androidAppId !== ''
        } else {
          this.disabled = false
        }
      },
    },
    dialogVisible: {
      deep: true,
      handler(val) {
        if (val) {
          this.initPage();
          customer().then(res => {
            this.customerList = res.data.data
          })
          getShareCustomer().then(res => {
            this.disableId = res.data.data
          })
          if (this.userInfo.is_agency === 0) {
            this.getURlList()
          }
        }
      }
    }
  },
  created() {
    this.getOptimizerList()
    this.getDesignerList()
    this.getDeptList()
  },
  mounted() {
    getSalesManager().then(res => {
      this.managerList = res.data.data

    })
    getCustomerManager().then(res => {
      this.customerManagerList = res.data.data

    })
    getSysDictList('platforms').then(map => {
      this.platformsList = map['platforms']
    })
    getGeoList().then(res => {
      this.nationList = res.data.data
      this.nationList.map((item) => {
        item.cnName = item.cnName + '-' + item.geoKey + '-' + item.geoName
      })
    })
    // customer().then(res => {
    //   this.customerList = res.data.data
    // })
    // getShareCustomer().then(res => {
    //   this.disableId = res.data.data
    // })
    getOfferList().then(res => {
      this.offerList = res.data.data
    })
    if (this.userInfo.is_agency == 1) {
      if (this.rules.isShared) {
        delete this.rules.isShared;
      }
    }
  },
  data() {
    var checkSystem = (rule, value, callback) => {
      if (!this.fillSubmlit()) {
        return callback(new Error('请输入android或ios'))
      } else {
        if (this.systemComplete()) {
          return callback(new Error('请将所填写的系统信息输入完整!'))
        } else {
          callback()
        }
      }
    }

    return {
      isSyncLevel: true,
      loading: false,
      urlLoading: false,
      urlconfirm: null,
      appDialogVisible: false,
      customerManagerList: [],
      managerList: [],
      imageUrl: '',
      addForm: {
        customerId: '',
        appUrl: '',
        isWebsite: false,
        name: '',
        os: 2,
        category: '',
        appPackageId: '',
        imageUrl: '',
      },
      osList: [
        {value: 1, label: 'Android'},
        {value: 2, label: 'ios'}
      ],
      formVisible: true,

      offerList: [],
      restaurants: [],
      state1: '',
      state2: '',
      state: '',
      iosDisable: false,
      androidDisable: false,
      checkOfferShareId: '',
      disabled: false,//不能输入
      editId: '',//编辑对象的id
      status: '',//编辑对象的状态
      platformsList: '',//平台列表
      nationList: [],//投放地区列表
      customerList: [], //客户列表
      openCheck: '',

      form: {
        customerId: '',//客户
        name: '',//offer名称
        productName: '',//产品名
        androidAppId: '',//android商店URL
        androidNation: [],//android投放投放地区
        androidPlatform: [],//android媒体
        iosAppId: '',//ios商店URL
        iosNation: [], //ios投放投放地区
        iosPlatform: [],//ios媒体
        websiteAppId: '',//website URL
        websiteNation: [],//website投放投放地区
        websitePlatform: [],//website媒体
        remark: '', //备注
        auditCreative: '',//广告主审核素材
        isShared: 0,//内部外部
        level: '',
        team: '' //团队
      },
      levelList: [
        {label: 'T1', value: 'T1'},
        {label: 'T2', value: 'T2'},
        {label: 'T3', value: 'T3'},
      ],
      rules: {
        customerId: [
          {required: true, message: '请选择客户', trigger: 'change'}
        ],
        name: [
          {required: true, message: '请输入订单名称', trigger: 'blur'}
        ],
        auditCreative: [
          {required: true, message: '请勾选广告主审核素材', trigger: 'change'}
        ],

        productName: [
          {required: true, message: '请输入产品名', trigger: 'change'}
        ],
        system: [
          {required: true, validator: checkSystem, trigger: 'change'}
        ],
        isShared: [
          {required: true, message: '请选择内部外部', trigger: 'change'}
        ],
        team: [
          {required:true, message:'请选择团队',trigger: 'change'}
        ]
      },
      addRules: {
        appUrl: [{required: true, message: '请输入商店url', trigger: 'blur'}],
        name: [{required: true, message: '请输入产品名称', trigger: 'blur'}]
      },
      disableId: [],
      isSharedDicData: [
        {label: '内部', value: 0},
        {label: '外部', value: 1},
      ],
      androidList: [],
      iosList: [],
      websiteList: [],
      app_save_loading: false,
      websiteHisAppUrl: '',
      normalHisAppUrl: '',
      // marco data
      // 优化师列表
      optimizerList: [],
      selectedOptimizers: [],
      // 设计师列表
      designerList: [],
      selectedDesigners: [],
      deptList: []
    }
  },
  methods: {
    initPage() {
      if (this.title == 'add') {
        this.form = {
          customerId: '',//客户
          name: '',//offer名称
          productName: '',//产品名
          androidAppId: '',//android商店URL
          androidNation: [],//android投放投放地区
          androidPlatform: [],//android媒体
          iosAppId: '',//ios商店URL
          iosNation: [], //ios投放投放地区
          iosPlatform: [],//ios媒体
          websiteAppId: '',//website URL
          websiteNation: [],//website投放投放地区
          websitePlatform: [],//website媒体
          remark: '', //备注
          auditCreative: '',//广告主审核素材
          isShared: 0,//内部外部
        };
        this.iosDisable = false;
        this.androidDisable = false;
      } else if (this.title == 'check') {
        this.iosDisable = true;
        this.androidDisable = true;
      } else if (this.title == 'edit' || this.title == 'copy') {
        if (this.form.status == 1 || this.form.status == 2) {
          this.iosDisable = this.form.iosUrl !== ''
          this.androidDisable = this.form.androidAppId !== ''
        } else {
          this.iosDisable = false;
          this.androidDisable = false;
        }
      }
    },
    urlConfim() {
      this.$refs['addForm'].validate((valid) => {
        if (valid) {
          this.urlLoading = true
          verifyProductUrl({customerId: this.addForm.customerId, appUrl: this.addForm.appUrl}).then(res => {
            console.log(res)
            this.$message.success('保存成功')
            this.urlLoading = false
            this.appDialogVisible = false
          }).catch((res) => {
            // this.$message.error('校验失败,请再次点击保存')
            // this.dialogForm.name = 'unknow'
            this.formVisible = true
            this.urlconfirm = false
            this.urlLoading = false
          })
        } else {
          return false
        }
      })
    },
    getOfferInfo(editId) {
      let self = this;
      if (self.offerList != null) {
        for (let i = 0; i < self.offerList.length; i++) {
          if (self.offerList[i].id === editId) {
            return self.offerList[i];
          }
        }
      }
      return null;
    },
    handleClose() {
      this.openCheck = '';
      this.$refs.form.resetFields();
      this.disabled = false;
      this.iosDisable = false;
      this.androidDisable = false;
      this.form.androidAppId = ''
      this.form.androidNation = []
      this.form.androidPlatform = []
      this.form.iosAppId = ''
      this.form.iosNation = []
      this.form.iosPlatform = []
      this.form.websiteAppId = ''
      this.form.websiteNation = []
      this.form.websitePlatform = []
      // this.androidList = [];
      // this.iosList = [];
      // this.websiteList = [];
      this.selectedOptimizers = []
      this.selectedDesigners = []
      this.$emit('close-dialog');
    },
    handleSubmit() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.userInfo.is_agency == 0 && this.form.isShared == 0) {
            this.form.auditCreative = false;
          }
          let form = {
            customerId: this.form.customerId,
            name: this.form.name,
            productName: this.form.productName,
            androidAppId: this.form.androidAppId,
            androidNation: this.form.androidNation.join(','),
            androidPlatform: this.form.androidPlatform.join(','),
            iosAppId: this.form.iosAppId,
            iosNation: this.form.iosNation.join(','),
            iosPlatform: this.form.iosPlatform.join(','),
            websiteAppId: this.form.websiteAppId,//website URL
            websiteNation: this.form.websiteNation.join(','),//website投放国家/地区
            websitePlatform: this.form.websitePlatform.join(','),//website媒体
            auditCreative: this.form.auditCreative ? '1' : '0',
            remark: this.form.remark,
            isShared: this.form.isShared,
            designers: this.selectedDesigners.join(','),
            opUsers: this.selectedOptimizers.join(','),
            team: this.form.team
            // level: this.form.level,
          }
          // let data = {
          //      id: this.form.customerId,
          //   level: this.form.level,
          // }
          // syncLevel(data).then(res =>{
          //   this.isSyncLevel = res.data;
          // })
          this.loading = true
          if (this.title == 'add' || this.title == 'copy') {
            this.rowSave(form)
          } else {
            form['id'] = this.editId
            form['status'] = this.status
            this.rowUpdate(form)
          }
        }
      });
    },
    fillSubmlit() {
      return (this.form.androidAppId !== '' && this.form.androidPlatform !== '' && this.form.androidNation !== '') ||
        (this.form.iosAppId !== '' && this.form.iosPlatform !== '' && this.form.iosNation !== '') ||
        (this.form.websiteAppId !== '' && this.form.websiteNation !== '' && this.form.websitePlatform !== '')
    },
    /**
     * 校验系统提交完整性
     * @param row
     * @param done
     */
    systemComplete() {
      if (this.form.androidAppId !== '' || this.form.androidPlatform.length !== 0 || this.form.androidNation.length !== 0) {
        return this.form.androidAppId === '' || this.form.androidPlatform == '' || this.form.androidNation == ''
      }
      if (this.form.iosAppId !== '' || this.form.iosPlatform.length !== 0 || this.form.iosNation.length !== 0) {
        return this.form.iosAppId === '' || this.form.iosPlatform == '' || this.form.iosNation == ''
      }
      if (this.form.websiteAppId !== '' || this.form.websitePlatform.length !== 0 || this.form.websiteNation.length !== 0) {
        return this.form.websiteAppId === '' || this.form.websitePlatform === '' || this.form.websiteNation === ''
      }
    },
    rowSave(row, done) {
      delete row.id
      add(row).then(() => {
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        this.handleClose()
        this.loading = false
        if (done) done();
      }, error => {
        this.loading = false
        window.console.log(error);
      });
    },
    rowUpdate(row, index, done) {
      update(row).then(() => {
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        this.handleClose()
        if (done) done();
        this.loading = false
      }, error => {
        this.loading = false
        console.log(error);
      });
    },
    analysis(val) {
      this.form = val
      this.form.androidNation = val.androidNation !== '' ? val.androidNation.split(',') : []
      this.form.androidPlatform = val.androidPlatform !== '' ? val.androidPlatform.split(',') : []
      this.form.iosNation = val.iosNation !== '' ? val.iosNation.split(',') : []
      this.form.iosPlatform = val.iosPlatform !== '' ? val.iosPlatform.split(',') : []
      this.form.websiteNation = val.websiteNation !== '' ? val.websiteNation.split(',') : []
      this.form.websitePlatform = val.websitePlatform !== '' ? val.websitePlatform.split(',') : []
      this.form.auditCreative = val.auditCreative == '1' ? true : false
      this.form.androidAppId = val.androidAppId != -1 ? val.androidAppId : '';
      this.form.iosAppId = val.iosAppId != -1 ? val.iosAppId : '';
      this.form.websiteAppId = val.websiteAppId !== -1 ? val.websiteAppId : '';
      this.selectedOptimizers = val.opUsers !== '' ? val.opUsers.split(',') : []
      this.selectedDesigners = val.designers !== '' ? val.designers.split(',') : []
      this.getURlList()
    },
    uploadQiniuCloud(file) {
      const that = this
      const fileData = qiniuTools.getFileData(file)
      const callback = {
        next(res) {
        },
        error(err) {
          this.$message.error("上传图片失败! err => " + err);
        },
        complete(res) {
          const url = 'http://' + fileData.server + '/' + res.key
          that.$set(that, 'imageUrl', url)
          // that.logoUrl = url
        }
      }
      const uploader = qiniuTools.uploadQiniuCloud(file, fileData)
      uploader.subscribe(callback)
    },
    beforeAvatarUpload(file) {
      var img = file.name.substring(file.name.lastIndexOf('.') + 1)
      const suffix = img === 'jpg'
      const suffix2 = img === 'png'
      const suffix3 = img === 'jpeg'
      const isLt1M = file.size / 1024 / 1024 < 1;
      if (!suffix && !suffix2 && !suffix3) {
        this.$message.error("只能上传图片！");
        return false
      }
      // 可以限制图片的大小
      if (!isLt1M) {
        this.$message.error('上传图片大小不能超过 1MB!');
      }
      return suffix || suffix2 || suffix3
    },
    /**
     * 新增App
     */
    addApp() {
      if (!this.form.customerId && this.userInfo.is_agency === 1) {
        this.$message({
          type: 'warning',
          message: '请选择客户进行新增!',
        })
        return
      }
      this.urlLoading = false
      this.urlconfirm = true
      this.formVisible = false
      this.addForm.appUrl = ''
      this.imageUrl = ''
      this.addForm.customerId = this.form.customerId
      this.appDialogVisible = true;
    },
    /**
     * 关闭新增App
     */
    handleAppClose() {
      this.appDialogVisible = false;
      let appUrl = this.addForm.appUrl
      //android
      getAppUrlSelect(this.form.customerId, 1).then(res => {
        if (res.data.data) {
          this.androidList = res.data.data
          this.echoUrl(appUrl);
        }
      })
      //ios
      getAppUrlSelect(this.form.customerId, 2).then(res => {
        if (res.data.data) {
          this.iosList = res.data.data
          this.echoUrl(appUrl);
        }
      })

      //website
      getAppUrlSelect(this.form.customerId, 3).then(res => {
        if (res.data.data) {
          this.websiteList = res.data.data
          this.echoUrl(appUrl);
        }
      })

      this.$refs.addForm.resetFields();
      this.websiteHisAppUrl = ''
      this.normalHisAppUrl = ''
    },
    /**
     * 获取url列表
     */
    getURlList() {
      //android
      getAppUrlSelect(this.form.customerId, 1).then(res => {
        if (res.data.data) {
          this.androidList = res.data.data
        }
      })
      //ios
      getAppUrlSelect(this.form.customerId, 2).then(res => {
        if (res.data.data) {
          this.iosList = res.data.data
        }
      })
      //website
      getAppUrlSelect(this.form.customerId, 3).then(res => {
        if (res.data.data) {
          this.websiteList = res.data.data
        }
      })
    },
    customerChange() {
      this.clearFormOS()
      this.getURlList()
    },
    /**
     * 新增App
     */
    saveApp() {
      this.$refs['addForm'].validate((visible) => {
        if (visible) {
          this.app_save_loading = true
          this.addForm.imageUrl = this.imageUrl
          console.log(this.addForm)

          addApp(this.addForm).then(res => {
            if (res.data.data) {
              this.$message({
                type: 'success',
                message: res.data.msg
              })
              this.app_save_loading = false
            }
            this.clearFormOS()
            this.handleAppClose();
          }, error => this.app_save_loading = false)
        } else {
          return false
        }
      })
    },

    /**
     * 新增APP成功回显URL
     */
    echoUrl(appUrl) {
      if (appUrl) {
        this.androidList.map(item => {
          if (appUrl === item.appUrl) {
            this.form.androidAppId = item.id
          }

        })
        this.iosList.map(item => {
          if (appUrl === item.appUrl) {
            this.form.iosAppId = item.id
          }
        })

        this.websiteList.map(item => {
          if (appUrl === item.appUrl) {
            this.form.websiteAppId = item.id
          }
        })
      }
    },
    websiteControl(isWebsite) {
      if (isWebsite) {
        this.normalHisAppUrl = this.addForm.appUrl
        this.addForm.appUrl = this.websiteHisAppUrl
        // this.addForm.os = 'website'
      } else {
        this.websiteHisAppUrl = this.addForm.appUrl
        this.addForm.appUrl = this.normalHisAppUrl
      }
    },
    // marco methods
    // 获取优化师列表
    async getOptimizerList() {
      try {
        const {data: res} = await getOptimizer()
        if (res.code !== 200) return
        this.optimizerList = res.data.map(item => {
          item.deptId = item.deptId === '' ? [] : item.deptId.split(',')
          return item
        })
        // console.log('优化师列表', res)
      } catch (err) {
        console.warn(err)
      }
    },
    async getDesignerList() {
      try {
        const {data: res} = await getDesignerSelect()
        if (res.code !== 200) return
        this.designerList = res.data.map(item => {
          item.deptId = item.deptId === '' ? [] : item.deptId.split(',')
          return item
        })
        // console.log('优化师列表', res)
      } catch (err) {
        console.warn(err)
      }
    },
    // 清空操作系统
    clearFormOS() {
      // this.form.androidAppId = ''
      // this.form.androidNation = []
      // this.form.androidPlatform = []
      // this.form.iosAppId = ''
      // this.form.iosNation = []
      // this.form.iosPlatform = []
      this.form.websiteAppId = ''
      this.form.websiteNation = []
      this.form.websitePlatform = []
    },
    async getDeptList() {
      const {data: res} = await getWorkrooms()
      this.deptList = res.data.map(item => {
        return {
          label: item.deptName,
          value: item.id
        }
      })
    },
    handleChangeTeam() {
      this.selectedDesigners = []
      this.selectedOptimizers = []
    }
  }
}

</script>
<style lang="scss" scoped>
/deep/ .el-drawer.rtl {
  overflow: scroll;
}

/deep/ .el-upload--picture {
  width: 120px;
  height: 120px;

}

.avatar {
  width: 190px;
  height: 190px;
}

.form-item {
  width: 60%;
}

.el-select__tags-text {
  display: inline-block;
  max-width: 120px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.el-select .el-tag__close.el-icon-close {
  top: -7px;
}

.addAppStyle {
  color: #409eff;
  font-size: 14px;
  cursor: pointer;
  float: right;
}

.offer-edit-container {
}

.el-select {
  width: 100%;
}
</style>
